package com.jml;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author:jml
 * @date: 2019/9/23 15:35
 * @description：Netty服务区的构建
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {

        // 用来接收accept事件,参数就是线程数默认是处理器数目的两倍
        EventLoopGroup parentGroup = new NioEventLoopGroup(1);
        // 处理读写事件
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            // 创建服务启动引擎
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 设置通道
            serverBootstrap.group(parentGroup, childGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            // 设置参数,接收缓冲区大小
            // serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,);
            // 设置参数,通道满了之后，阻塞的允许有128个排队
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 128)
                // 设置参数,
                .option(ChannelOption.SO_KEEPALIVE, true)
                // 设置参数 ,从线程去添加一个handler处理，
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override // 这是一个初始化的handler，对通道初始化
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // Delimiters.lineDelimiter()[0]表示分隔符
                        // 解码器
                        ch.pipeline()
                            .addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));

                        ch.pipeline().addLast(new SimpleHandle());

                        ch.pipeline().addLast(new StringEncoder());
                    }
                });

            // 绑定端口，并且同步返回
            ChannelFuture future = serverBootstrap.bind(8080).sync();
            // 同步关闭
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }
    }
}
